﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Text.RegularExpressions;

namespace ComiKamiQ
{
    abstract class DUtil : Comic
    {
        public abstract IList<Chapter> SpiderChapters(string url=null);
        public abstract IList<Page> SpiderPages(Chapter chapter);

        public static Regex reQuote = new Regex("(?<=\").*?(?=\")", RegexOptions.Compiled);
        public static Regex reHref = new Regex("(?<=href=\").*?(?=\")", RegexOptions.Compiled);
        
        protected static Microsoft.JScript.Vsa.VsaEngine jsEngine = Microsoft.JScript.Vsa.VsaEngine.CreateEngine();

        //public 

        public DUtil(string url, string root = "", int chapterNameConfig = 0, int pageNameConfig = 0)
            : base(url, root, chapterNameConfig, pageNameConfig)
        { }

        public static string LoadHtml(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            string html = "";
            // Set some reasonable limits on resources used by this request
            request.MaximumAutomaticRedirections = 4;
            request.MaximumResponseHeadersLength = 4;
            // Set credentials to use for this request.
            HttpWebResponse response;
            request.Credentials = CredentialCache.DefaultCredentials;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            Stream receiveStream;
            StreamReader readStream;
            receiveStream = response.GetResponseStream();
            if (response.ContentEncoding != "")
            {
                if (response.ContentEncoding.ToLower().Contains("gzip"))
                    receiveStream = new GZipStream(receiveStream, CompressionMode.Decompress);
                else return null;//if (response.ContentEncoding.ToLower().Contains("gzip"))
            }
            readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
            html = readStream.ReadToEnd();
            response.Close();
            readStream.Close();

            return html;
        }

        public static string JScriptEval(string expression)
        {
            string jsResultStr;
            object jsResultObj;
            try
            {
                jsResultObj = Microsoft.JScript.Eval.JScriptEvaluate(expression, jsEngine);
                jsResultStr = jsResultObj.ToString();
            }
            catch (Exception ex)
            {
                //throw ex;
                return null;
            }
            return jsResultStr;
        }
    }

}
